﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using CodeTier.BUL;
using CodeTier.DAL;
using System.IO;
using System.Runtime.InteropServices;

namespace Quanly
{
    public partial class Frm_QuanLiSanPham : Frm_Abstract
    {
        IList<SanPhamBUS> lst_sp;
        IList<DanhMucBUS> lst_dm;

        public Frm_QuanLiSanPham()
        { 
            InitializeComponent();
            clear();
            loadData();
        }

        public void loadData()
        {
            lst_sp = SanPhamBUS.getAll();
            lst_dm = DanhMucBUS.getAll();
            loadToControl();
        }

        public void loadToControl()
        {
            loadSanPham();
            loadLoai();
        }

        public void loadSanPham()
        {
            if (lst_sp == null)
            {
                MessageBox.Show("Error load database", "Error Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.lstProducts.Items.Clear();
                foreach (SanPhamBUS pro in lst_sp)
                {
                    addProductIntoListview(pro);
                }
            }
        }

        public void addProductIntoListview(SanPhamBUS pro)
        {
            ListViewItem item;
            item = this.lstProducts.Items.Add(pro.MaSP.ToString());
            item.SubItems.Add(pro.TenSP);
            DanhMucBUS dm = new DanhMucBUS(pro.MaDM);
            item.SubItems.Add(dm.TenDM);
            item.SubItems.Add(pro.SLTonKho.ToString());
            item.SubItems.Add(pro.DonGia.ToString());         
        }

        public void clear()
        {
            txtName.Text = null;
            //cboCategory.Items.Clear();
            txtPrice.Value = 0;
            txtQuantityInStock.Text = "0";
            picImage.Image = null;
            rtbDescription.Text = null;
            ofdImage.FileName = null;
        }

        public void loadLoai()
        {
            cboCategory.DataSource = lst_dm;            
            cboCategory.DisplayMember = "TenDM";
            cboCategory.ValueMember = "MaDM";
        }

        public SanPhamBUS makeProduct(bool bl)//true la add new, false la update
        {
            SanPhamBUS sp = new SanPhamBUS();
            if (bl == false)
            {
                sp.MaSP = Convert.ToInt32(lstProducts.SelectedItems[0].SubItems[0].Text);
            }
            sp.TenSP = txtName.Text;
            sp.MoTa = rtbDescription.Text;
            sp.SLTonKho = Convert.ToInt32(txtQuantityInStock.Text);
            sp.DonGia = Convert.ToInt32(txtPrice.Value);
            sp.MaDM = Convert.ToInt32(cboCategory.SelectedValue);
            sp.NgayDang = DateTime.Now;
            sp.TinhTrang = "1";
            string path = ofdImage.FileName;
            if (!string.IsNullOrEmpty(path))
            {
                string name = path.Substring(path.LastIndexOf("\\")).Remove(0, 1);
                Image img = Image.FromFile(path);
                byte[] b = cImageConverter.ImageToBytes(img);
                sp.HinhAnh = b;
                //string desPath = @"../../Images/Products/" + name;
                //if (!File.Exists(desPath))
                //{
                //    File.Copy(path, desPath);
                //}
                //sp.HinhAnh = name;
            }

            return sp;
        }

        public bool checkSaveValidation()
        {
            if (ofdImage == null)
                return false;

            string path = ofdImage.FileName;
            if (txtName.Text == null
                || cboCategory.SelectedIndex == -1
                || string.IsNullOrEmpty(path))
            {
                return false;
            }
            return true;
        }

        public bool checkUpdateValidation()
        {
            string path = ofdImage.FileName;
            if (txtName.Text == null
                || cboCategory.SelectedIndex == -1
                )
            {
                return false;
            }
            return true;
        }

        public override void save()
        {
            if (checkSaveValidation())
            {
                SanPhamBUS sp = makeProduct(true);
                if (sp != null)
                {
                    if (SanPhamBUS.insert(sp))
                    {
                        lst_sp.Add(sp);
                        refresh();
                        MessageBox.Show("Cập Nhật Thành Công");
                        clear();
                    }
                }
            }
            else
            {
                MessageBox.Show("thông tin không đúng");
            }            
        }

        public override void update()
        {
            if (lstProducts.SelectedItems.Count > 0)
            {
                if (checkUpdateValidation())
                {
                    SanPhamBUS sp = makeProduct(false);
                    if (sp != null)
                    {
                        if (sp.update())
                        {
                            clear();
                            refresh();
                            MessageBox.Show("Cập Nhật Thành Công");
                        }
                    }
                }
            }
        }

        public override void delete()
        {
            if (lstProducts.SelectedItems.Count != 0)
            {
                SanPhamBUS sp = new SanPhamBUS();
                sp.MaSP = Convert.ToInt32(lstProducts.SelectedItems[0].Text);
                if (sp.delete())
                {
                    clear();
                    refresh();
                    MessageBox.Show("xóa thành công");
                }
                else
                {
                    MessageBox.Show("Không Thể Xóa");
                    lstProducts.SelectedItems.Clear();
                }
            }
        }

        public override void closeForm()
        {
            this.Close();
        }

        public override void refresh()
        {
            loadData();
        }

        private void lstProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            clear();
            if (lstProducts.SelectedItems.Count != 0)
            {
                loadDataToControl();
            }
        }

        public void loadDataToControl()
        {
            SanPhamBUS sp = SanPhamBUS.getByIdConvert(Convert.ToInt32(lstProducts.SelectedItems[0].Text));
            txtName.Text = sp.TenSP;
            cboCategory.SelectedValue = sp.MaDM;
            txtPrice.Value = sp.DonGia;
            txtQuantityInStock.Text = sp.SLTonKho.ToString();
            this.picImage.Image = cImageConverter.BytesToImage(sp.HinhAnh);
            rtbDescription.Text = sp.MoTa;
            //if (sp.HinhAnh != null)
            //{
            //    this.picImage.ImageLocation = @"..\..\Images\Products\" + sp.HinhAnh;
            //}
            //else
            //{
            //    this.picImage.Image = new Bitmap(Application.StartupPath + "\\defaultImage.png");
            //}  
        }

        private void btnBowse_Click(object sender, EventArgs e)
        {
            try
            {
                this.ofdImage.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif;  *.bmp";
                if (this.ofdImage.ShowDialog() == DialogResult.OK)
                {
                    //set new image
                    this.picImage.Image = new Bitmap(this.ofdImage.FileName);
                }
                //else
                //{
                //    //no change image
                //    this.picImage.Image = new Bitmap(Application.StartupPath + "\\defaultImage.png");
                //}
               
            }
            catch (Exception)
            {
                throw new ApplicationException("Failed loading image");
            }
        }

        private void bnt_Nhap_Click(object sender, EventArgs e)
        {
            Frm_NhapSL nhap = new Frm_NhapSL();
            nhap.ShowDialog();
            if (nhap.DialogResult == DialogResult.OK)
            {
                try
                {
                    txtQuantityInStock.Text = (Convert.ToInt32(txtQuantityInStock.Text) + Convert.ToInt32(nhap.txt_SL.Text)).ToString();
                }
                catch (Exception) { }
            }
        }







    }
}